package com.leet.code.simple_array;

public class AddTwoNumbers {

    public static void main(String[] args) {
	    // write your code here
        ListNode node = new ListNode(2, new ListNode(4, new ListNode(5)));
        ListNode node1 = new ListNode(5, new ListNode(6, new ListNode(4)));
        ListNode res = addTwoNumbers(node, node1);
        System.out.println(res);
    }
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int res = 0;
        ListNode result = null;
        ListNode tail = null;
        while (l1 != null || l2 != null) {
            int n1 = l1 != null ? l1.val : 0;
            int n2 = l2 != null ? l2.val : 0;
            int sum = n1 + n2 + res;
            res = sum / 10;
            if (result == null) {
                result = tail = new ListNode(sum % 10);
            } else {
                tail.next = new ListNode(sum % 10);
                tail = tail.next;
            }
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        if (res > 0) {
            tail.next = new ListNode(res);
        }
        return result;
    }

    public static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    ", next=" + next +
                    '}';
        }
    }
}
